/**
 * @Title: Tool.java
 * @Package com.dspsemi.diancaiba.utils
 * @author guoyunfeng
 * @date 2014-11-18 下午1:20:04
 * @version V1.5
 */
package com.dahua.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.DisplayMetrics;


/**
 * @Description: 工具类
 * @author guoyunfeng
 * @date 2014-11-18 下午1:20:04
 * @version V1.5
 */
public class Tool {

    private static DisplayMetrics dm;

    public static void initMe(Object object) {
        Method[] methods = object.getClass().getDeclaredMethods();
        if (methods == null || methods.length == 0) {
            return;
        }
        for (Method method : methods) {
            if (isInitMethod(method)) {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                try {
                    method.invoke(object);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * @param method
     * @return
     */
    private static boolean isInitMethod(Method method) {
        return method.getName().startsWith("init")
                && method.getReturnType().equals(Void.TYPE)
                && !method.isVarArgs()
                && !Modifier.isAbstract(method.getModifiers());
    }

    /**
     * 时间戳转换成时间字符串
     *
     * @param chuo
     * @return
     */
    public static String getTimeToStringAll(String chuo) {
        return getTimeToStringAll(chuo, "yyyy-MM-dd HH:mm");
    }

    /**
     * 时间戳转换成时间字符串
     *
     * @param chuo
     * @return
     */
    public static String getTimeToStringAll(String chuo, String format) {
        String time = null;

        if (chuo == null || "".equals(chuo)) {
            time = "时间未知";
            return time;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = sdf.format(new Date(Long.parseLong(chuo)));
        time = date;
        return time;
    }


    public static synchronized DisplayMetrics getMetrics(Activity context) {
        if (dm == null) {
            dm = new DisplayMetrics();
        }
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    public static String postToServer(String url, String... parameters)
            throws ParseException, IOException {
        if (parameters == null) {
            throw (new IOException("参数为空, 至少要传个KEY吧"));
        }
        if (parameters.length % 2 != 0) {
            throw (new IOException("参数数量不对, 变量名和值要成对出现"));
        }
        List<NameValuePair> paraList = new ArrayList<NameValuePair>();
        NameValuePair pair = null;
        for (int i = 0; i < parameters.length / 2; i++) {
            pair = new BasicNameValuePair(parameters[i * 2],
                    parameters[i * 2 + 1]);
            paraList.add(pair);
        }
        return postToServer(url, paraList);
    }

    private static String postToServer(String url,
                                       List<NameValuePair> parameters) throws ParseException, IOException {

        HttpClient client = null;
        String res = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            BasicHttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,
                    /* Constant.TIMEOUT_CONNECTION */5000);
            HttpConnectionParams.setSoTimeout(httpParams,
                    /* Constant.TIMEOUT_SOCKET */5000);
            httpPost.setParams(httpParams);
            HttpEntity entity = null;
            String error = null;
            entity = new UrlEncodedFormEntity(parameters, "UTF-8");
            String string = EntityUtils.toString(entity, HTTP.UTF_8);
            System.out.println("post is: " + string);
            httpPost.setEntity(entity);
            client = new DefaultHttpClient();
            HttpResponse response = client.execute(httpPost);
            if (response != null
                    && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                res = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
                System.out.println("response is: " + res);
                // sendMessage(MESSAGE_LONGIN_SUCCESS, result.getMessage());
            }
            return res;
        } finally {
            if (client != null) {
                client.getConnectionManager().shutdown();
            }
        }
    }

    /**
     * 判断手机号码是否正确
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * validate email's format
     *
     * @param email
     * @return
     */
    public static boolean isEmailValid(String email) {
        String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        return email.matches(regex);
    }

//	public static InputStream getStreamFromURL(String url) throws IOException {
//		// 获取数据
//		int timeoutConnection = Constants.TIMEOUT_CONNECTION;
//		int timeoutSocket = Constants.TIMEOUT_SOCKET;
//		HttpParams httpParameters = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParameters,
//				timeoutConnection);
//		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
//
//		DefaultHttpClient client = new DefaultHttpClient(httpParameters);
//		HttpGet get = new HttpGet(url);
//		HttpResponse resp = client.execute(get);
//		HttpEntity entity = resp.getEntity();
//		return entity.getContent();
//	}

    /**
     * 判断sd卡是否可用，如果可用返回路径
     *
     * @return sd卡路径
     */
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        if (sdDir == null) {
            return "";
        }
        return sdDir.toString();
    }

    /**
     * 提示
     *
     * @param context
     * @param text
     */
//	public static void showText(Context context, String text) {
//		// Toast.makeText(context, text, Toast.LENGTH_LONG).show();
//		ToastUtils.showToast(context, text);
//	}

    /**
     * 得到当前versionCode
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static Bitmap decodeBmpFromFile1(String path) {
        InputStream in = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Config.ARGB_8888;
            options.inPurgeable = true;// 允许可清除
            options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果
            in = new FileInputStream(path);
            return BitmapFactory.decodeStream(in, null, options);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static Bitmap decodeBmpFromFile(String path) {
        BitmapFactory.Options bfOptions = new BitmapFactory.Options();
        bfOptions.inDither = false;
        bfOptions.inPurgeable = true;
        bfOptions.inTempStorage = new byte[12 * 1024];
        // bfOptions.inJustDecodeBounds = true;
        File file = new File(path);
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bmp = null;
        if (fs != null)
            try {
                bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null,
                        bfOptions);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fs != null) {
                    try {
                        fs.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        return bmp;
    }

    public static void clearBitmapInfo(Context context) {
//		BitmapInfo info = new BitmapInfo(context);
//		info.loadData();
//		deleteTempFile(info);
//		info.setLength(0);
//		info.saveData();
    }

//	private static void deleteTempFile(BitmapInfo info) {
//		int count = info.getLength();
//		String url = null; 
//		String path = null;
//		for (int i = 0; i < count; i ++) {
//			url = info.getUrl(i);
//			if (url != null) {
//				path = info.getPath(i);
//				if (path != null) {
//					new File(path).delete();
//				}
//			}
//		}
//	}

}
